package com.Jhu1.controller;

import com.Jhu1.entity.Product;
import com.Jhu1.service.IProductService;
import com.Jhu1.util.PageResult;
import com.Jhu1.util.R;
import com.Jhu1.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 钟俊辉
 * @since 2025-01-11
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;
    @RequestMapping("/list")
    public R getProduct(){
        return R.ok().data("list", productService.list());
    }
    //分页
    @GetMapping("/findByPage/{page}/{pageSize}")
    public R findByPage(@PathVariable("page") Integer page,
                        @PathVariable("pageSize") Integer pageSize) {
        PageResult<Product> pr = productService.findByPage(page,pageSize);
        return R.ok().data("pageResult",pr);
    }
    //条件查询加上分页
    @PostMapping("/searchProduct/{page}/{pageSize}")
    public R searchProduct(@PathVariable("page") Integer page,
                           @PathVariable("pageSize") Integer pageSize,
                           @RequestBody(required = false) ProductVO vo){
        PageResult<Product> pageResult = productService.searchProduct(page,pageSize,vo);
        return R.ok().data("pageResult",pageResult);
    }
    @PostMapping("/addProduct")
    public R addStudent(@RequestBody Product product){
        System.out.println("!111");
        boolean flag = productService.save(product);
        System.out.println("2222");
        return flag ? R.ok().message("添加商品成功!") : R.error().message("添加商品失败!");
    }

    @PutMapping("/updateProduct")
    public R updateStudent(@RequestBody Product product){
        boolean flag = productService.updateById(product);
        return flag ? R.ok().message("修改商品成功!") : R.error().message("修改商品失败!");
    }
    @DeleteMapping("/delete/{ids}")
    public R delete(@PathVariable("ids") String ids){  // 1,2,3
        String[] split = ids.split(",");
        List<String> sids = Arrays.asList(split);
        return productService.removeByIds(sids) ? R.ok().message("删除商品成功!") : R.error().message("删除商品失败!");
    }
}
